package com.culture.config.model;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.util.Assert;

import com.culture.config.dao.entity.UserRole;

import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

@Data
@Accessors(chain=true)
@NoArgsConstructor
public class RoleGrantedAuthority implements GrantedAuthority {	
	private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;	
	private static final String ROLE_PREFIX = "ROLE_";	
	private UserRole userRole;
	private String roleName;	
	
	public RoleGrantedAuthority(UserRole userRole) {
		Assert.notNull(userRole,"A granted authority role representation is required");
		Assert.hasText(userRole.getRoleName(), "A granted authority role textual representation is required");
		this.userRole = userRole;
		this.roleName = StringUtils.join(ROLE_PREFIX, userRole.getRoleName());		
	}
	
	@Override
	public String getAuthority() {
		return this.roleName;
	}
	
	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}

		if (obj instanceof RoleGrantedAuthority) {
			return this.roleName.equals(((RoleGrantedAuthority) obj).roleName);
		}

		return false;
	}

	@Override
	public int hashCode() {
		return this.roleName.hashCode();
	}

	@Override
	public String toString() {
		return this.roleName;
	}

}
